package com.iot.common.utils;

import org.springframework.core.NamedThreadLocal;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Cao.ning
 * @date 2022/11/10
 * @desc 计算耗时工具类 start与end需要成对出现，否则会导致计算错误或存在内存泄露风险
 */
public class TimeHelper {

    private static final NamedThreadLocal<Map<String, Long>> TIME_TL = new NamedThreadLocal<>("TIME_TL");

    /**
     * 根据key开始计时
     *
     * @param timeKey
     */
    public static void start(String timeKey) {
        Map<String, Long> timeMap = TIME_TL.get();
        if (timeMap == null) {
            timeMap = new HashMap<>();
        }
        timeMap.put(timeKey, System.currentTimeMillis());
        TIME_TL.set(timeMap);
    }

    /**
     * 根据key计算耗时
     *
     * @param timeKey
     * @return
     */
    public static Long end(String timeKey) {
        try {
            Map<String, Long> timeMap = TIME_TL.get();
            return System.currentTimeMillis() - timeMap.get(timeKey);
        } catch (Exception ex) {
            return -1L;
        } finally {
            TIME_TL.remove();
        }
    }
}